package cn.buaa.edu.cn.ffmpegservice.service.impl;

import cn.buaa.edu.cn.ffmpegservice.config.JsonResult;
import cn.buaa.edu.cn.ffmpegservice.service.IRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RequiredArgsConstructor
public class RecordServiceImpl implements IRecordService {

    private final AsyncService asyncService;

    @Override
    public JsonResult<?> beginRecord(String instanceID) {
        JsonResult<?> result = new JsonResult<>();
        try {
            if (asyncService.getProcess() != null) {
                asyncService.endTask();
                System.out.println(">>>>>>>>>>推流视频切换<<<<<<<<<<");
            }
            asyncService.doTask(instanceID);
        } catch (IOException e) {
            e.printStackTrace();
            result.setInfo(e.getMessage());
            result.setStatus("error");
        }
        return result;
    }

    @Override
    public JsonResult<?> endRecord(String instanceID) {
        JsonResult<?> result = new JsonResult<>();
        if (null == asyncService.getProcess()) {
            result.setStatus("error");
            result.setInfo("推流进程不存在，无效终止");
        } else {
            try {
                result.setInfo( asyncService.endTask());
            } catch (IOException e) {
                result.setStatus("error");
                result.setInfo("[停止推流失败]" + e.getMessage());
            }
            System.out.println(">>>>>>>>>>结束视频推流" + instanceID + "<<<<<<<<<<");
        }
        return result;
    }
}
